package com.lcc.book.demos.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcc.book.demos.web.Model.Result;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@ControllerAdvice
public class Responseadvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
//        return false;
        return true;//改成返回true才生效
    }

    @SneakyThrows//该注解能够在编译之后生成try catch
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
       //在返回之前需要做的事情，也就是在controller的接口在返回响应之前需要做的事情
        //对返回的响应数据进行封装
        //当返回结果就为Result类型的时候避免进行重复封装
        if (body instanceof Result){
            return body;
        }
        if(body instanceof String){
            return objectMapper.writeValueAsString(Result.success(body));//使用注解@SneakyThrows代替抛异常
        }
        return Result.success(body);
//        return null;
    }
}
